/****************************************************
	文件：EventContext.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2021/2/8 10:11:25
	功能：事件上下文
*****************************************************/

using System;
using System.Collections.Generic;

namespace HTFW.Core
{
    public class EventContext : IContext
    {
        /// <summary>
        /// 内部事件集合（任意参数）
        /// </summary>
        Dictionary<EventType, List<HCallBack>> mEventDict;

        public ContextType ContextType { get; set; }
        public ContextScope ContextScope { get; set; }
        public Action<IContext> OnInit { get; set; }
        public Action<IContext> OnDispose { get; set; }


        public void Init(params object[] args)
        {
            mEventDict = new Dictionary<EventType, List<HCallBack>>();
        }

        public void Dispose()
        {
            DisposeAllEvents();
            mEventDict = null;

            OnInit = null;
            OnDispose = null;
        }

        /// <summary>
        /// 注册事件
        /// </summary>
        /// <param name="eventType"></param>
        /// <param name="callBack"></param>
        public void Subscribe(EventType eventType, HCallBack callBack)
        {
            EventCenter.Subscribe(eventType, callBack);

            if (mEventDict.ContainsKey(eventType))
            {
                mEventDict[eventType].Add(callBack);
            }
            else
            {
                List<HCallBack> cbLst = new List<HCallBack>();
                cbLst.Add(callBack);
                mEventDict.Add(eventType, cbLst);
            }
        }

        /// <summary>
        /// 注销事件
        /// </summary>
        /// <param name="eventType"></param>
        /// <param name="callBack"></param>
        public void Unsubscribe(EventType eventType, HCallBack callBack)
        {
            if (mEventDict.TryGetValue(eventType, out var cbLst))
            {
                if (cbLst.Contains(callBack))
                {
                    cbLst.Remove(callBack);
                    if (cbLst.Count <= 0)
                        mEventDict.Remove(eventType);
                    EventCenter.Unsubscribe(eventType, callBack);
                }
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="eventType"></param>
        /// <param name="p"></param>
        public void Publish(EventType eventType, params object[] p)
        {
            EventCenter.Publish(eventType, p);
        }

        /// <summary>
        /// 注销内部事件
        /// </summary>
        void DisposeAllEvents()
        {
            foreach (var item in mEventDict)
            {
                foreach (var cb in item.Value)
                    EventCenter.Unsubscribe(item.Key, cb);
            }

            mEventDict.Clear();
        }
    }
}